<template>
    <div id='ArtCmt' :style="{ paddingBottom: editMode ? '26.66666vw' : '12.26666vw' }" ref="cmtRef">
        <!-- 评论列表 -->
        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="scopeComments">
            <div class="body-wrap" v-for="item in commentsList" :key="item.com_id">
                <div class="info">
                    <div class="face"><img :src="item.aut_photo" alt=""></div>
                    <div class="name">{{ item.aut_name }}</div>
                    <van-icon name="like-o" v-if="!item.is_liking" @click="likeComment(item.com_id)" />
                    <van-icon name="like" v-else class="liked" @click="cancelLike(item.com_id)" />
                </div>
                <div class="body">
                    {{ item.content }}
                </div>
                <div class="time">
                    {{ formatTime(item.pubdate) }}
                </div>
            </div>
        </van-list>

        <!-- 评论框 -->
        <div class="cmt-wrap">
            <div class="add-cmt-wrap" v-if="!editMode">
                <van-icon name="arrow-left" size="4.8vw" @click="router.back()" />
                <div class="fakeInput" @click="editMode = true">
                    <p>发表评论</p>
                </div>
                <div class="icon-box">
                    <van-badge :content="commentsInfo.count >= 100 ? '99+' : commentsInfo.count">
                        <van-icon name="comment-o" @click="emits('scroll-to-cmt', cmtRef.offsetTop - 340)" />
                    </van-badge>
                    <van-icon :color="collected ? '#ed712e' : '#000'" :name="collected ? 'star' : 'star-o'"
                        @click="favoriteArticle" />
                    <van-icon name="share-o" @click="Toast.fail('暂未开放')" />
                </div>
            </div>
            <div class="edit-cmt-wrap" v-else>
                <textarea ref="textareaRef" v-model="issueVal" @blur="editMode = false"
                    placeholder="友善评论，理性发言，阳光心灵"></textarea>
                <div class="issue-btn" @mousedown="issueComment" :style="{ color: issueBtnColor }">发布</div>
            </div>
        </div>
    </div>
</template>

<script  setup>
import { Icon as vanIcon, Toast, Badge as vanBadge, List as vanList } from 'vant'
import { reactive, ref, watch, defineEmits, defineProps } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getComments, commentLike, commentUnLike, postComment, articleFavorite, articleUnfavorite } from '@/api'
import moment from 'moment'
const router = useRouter()
const route = useRoute()

const props = defineProps({
    collected: {
        type: Boolean,
        default: false
    }
})

const editMode = ref(false)
// 编辑框焦点自动聚焦
const textareaRef = ref(null)
const timer = () => textareaRef.value.focus()
watch(editMode, (newVal) => {
    if (newVal) setTimeout(timer, 100)
    else clearTimeout(timer)
})

const cmtRef = ref(null)
const emits = defineEmits(['scroll-to-cmt', 'change-collected'])
// 获取评论信息
const loading = ref(false)
const finished = ref(false)
const commentsList = ref([])
const commentsInfo = reactive({})
const scopeComments = async () => {
    Toast.loading({
        message: '加载中...',
        forbidClick: true
    })
    loading.value = true
    const { data: { data } } = await getComments(route.params.id, commentsInfo.lastId)
    commentsList.value = [...commentsList.value, ...data.results]
    commentsInfo.endId = data.end_id
    commentsInfo.lastId = data.last_id
    commentsInfo.count = data.total_count
    loading.value = false
    finished.value = data.total_count <= commentsList.value.length
    Toast.clear()
}

// 发表评论
const issueVal = ref('')
const issueBtnColor = ref('#999')
watch(issueVal, (newVal) => {
    if (newVal.length > 0) {
        issueBtnColor.value = '#3579f7'
    } else {
        issueBtnColor.value = '#999'
    }
})
const issueComment = async () => {
    if (!issueVal.value) {
        Toast.fail('请输入评论内容')
        return
    }
    Toast.loading({
        message: '发布中...',
        forbidClick: true
    })
    try {
        const { data: { data } } = await postComment(route.params.id, issueVal.value)
        Toast.clear()
        Toast.success({
            message: '发布成功'
        })
        commentsInfo.count++
        commentsList.value.unshift(data.new_obj)
        issueVal.value = ''
    } catch {
        Toast.clear()
        Toast.fail('发布失败')
    }
}
// 点赞评论
const likeComment = async (id) => {
    try {
        const { data: { message } } = await commentLike(id)
        if (message === 'OK') {
            commentsList.value.forEach(item => {
                if (item.com_id === id) item.is_liking = true
            })
        }
    } catch {
        Toast.fail('点赞失败')
    }
}
// 取消点赞
const cancelLike = async (id) => {
    try {
        await commentUnLike(id)
        commentsList.value.forEach(item => {
            if (item.com_id === id) item.is_liking = false
        })
    } catch {
        Toast.fail('操作失败')
    }
}
// 收藏文章 / 取消收藏
const favoriteArticle = async () => {
    try {
        if (props.collected) {
            await articleUnfavorite(route.params.id)
        } else {
            await articleFavorite(route.params.id)
        }
        emits('change-collected', !props.collected)
        Toast.success({
            message: props.collected ? '取消收藏成功' : '收藏成功'
        })
    } catch {
        Toast.fail('操作失败')
    }
}
// 日期格式化函数
const formatTime = (time) => {
    const res = Math.abs(parseInt(moment(time, 'YYYY-MM-DD hh:mm:ss').diff(moment()) / 1000))

    if (res < 60) return `${res} 秒前`
    else if (res < 3600) return `${Math.floor(res / 60)} 分钟前`
    else if (res < 86400) return `${Math.floor(res / 3600)} 小时前`
    else if (res < 604800) return `${Math.floor(res / 86400)} 天前`
    else if (res < 2592000) return `${Math.floor(res / 604800)} 周前`
    else if (res < 31536000) return `${Math.floor(res / 2592000)} 月前`
    else return `${Math.floor(res / 31536000)} 年前`
}
</script>

<style lang='less'>
#ArtCmt {
    .body-wrap {
        display: flex;
        flex-direction: column;
        align-items: space-between;
        justify-content: center;
        padding: 20px 15px;
        border-bottom: 1px solid #f0f0f0;

        .info {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .face {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                overflow: hidden;

                img {
                    width: 100%;
                    height: 100%;
                }
            }

            .name {
                flex: 1;
                padding-left: 15px;
                padding-right: 50px;
                // 溢出隐藏
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            .van-icon {
                font-size: 16px;
            }

            .liked {
                color: #ff6700;
            }
        }

        .body {
            font-size: 14px;
            padding: 15px;
        }

        .time {
            font-size: 12px;
            color: #999;
        }
    }

    .cmt-wrap {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        box-shadow: 0 -1px 5px rgba(0, 0, 0, .05);
        background-color: #fff;
        z-index: 999;

        .add-cmt-wrap {
            display: flex;
            justify-content: start;
            align-items: center;
            height: 46px;
            padding: 0 15px;
            background-color: rgba(0, 0, 0, .01);

            .fakeInput {
                flex: 1;
                display: flex;
                align-items: center;
                margin-left: 10px;
                padding-left: 15px;
                height: 36px;
                border-radius: 18px;
                background-color: #f3f3f3;
                font-size: 12px;
            }

            .icon-box {
                display: flex;
                align-items: center;
                font-size: 20px;
                padding: 0 10px 0 20px;

                >:nth-child(2) {
                    margin: 0 20px;
                }
            }
        }

        .edit-cmt-wrap {
            padding: 10px;
            display: flex;
            justify-content: space-between;

            textarea {
                width: 85%;
                height: 80px;
                border: none;
                outline: none;
                font-size: 14px;
                resize: none;
                padding: 10px;
                background-color: #f2f2f2;
                border-radius: 10px;

                ::before {
                    color: #666;
                    font-size: 12px;
                }
            }

            .issue-btn {
                flex: 1;
                display: flex;
                justify-content: center;
                align-items: center;
                color: #666;
            }
        }
    }
}
</style>
